# -*- coding: utf-8 -*-

# Copyright (c) Huoty, All rights reserved
# Author: Huoty <sudohuoty@163.com>
# CreateTime: 2020-10-30 14:05:31


#!/usr/bin/env python
# coding: utf-8
"""
python test_signal.py -s 12
python test_signal.py -s 12  --sleep
python test_signal.py -s 12  -i
python test_signal.py -s 12  -i --sleep
python test_signal.py -s 12  -c
python test_signal.py -s 12  -c --sleep

测试结果:
[12:38:46] yipingan@offline3:~/jqcore/study$ python test_signal.py -s 12
thread_worker start
kill self by 12
User defined signal 2
[12:38:47] yipingan@offline3:~/jqcore/study$ python test_signal.py -s 12  --sleep
thread_worker start
kill self by 12
User defined signal 2
[12:38:48] yipingan@offline3:~/jqcore/study$ python test_signal.py -s 12  -i
thread_worker start
kill self by 12
kill self by 9
Killed
[12:38:52] yipingan@offline3:~/jqcore/study$ python test_signal.py -s 12  -i --sleep
thread_worker start
kill self by 12
kill self by 9
Killed
[12:38:56] yipingan@offline3:~/jqcore/study$ python test_signal.py -s 12  -c
thread_worker start
kill self by 12
signal handler 12 <frame object at 0x1f520b0>
kill self by 9
Killed
[12:39:00] yipingan@offline3:~/jqcore/study$ python test_signal.py -s 12  -c --sleep
thread_worker start
kill self by 12
signal handler 12 <frame object at 0x1f450b0>
main thread exit
"""
from __future__ import print_function, unicode_literals
import os
import sys
import threading
import time
import signal

def main(args):
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('-d', '--debug', action='store_true')
    parser.add_argument('-s', '--signal', type=int, required=True)
    parser.add_argument('-i', '--ignore-signal', action='store_true')
    parser.add_argument('-c', '--catch-signal', action='store_true')
    parser.add_argument('--sleep', action='store_true')
    options = parser.parse_args()
    if options.ignore_signal:
        signal.signal(options.signal, signal.SIG_IGN)
    if options.catch_signal:
        def handler(signo, frame):
            print('signal handler', signo, frame)
            pass
        signal.signal(options.signal, handler)
    def thread_worker():
        print('thread_worker start')
        time.sleep(1)
        print("kill self by", options.signal)
        os.kill(os.getpid(), options.signal)
        time.sleep(3)
        print("kill self by", 9)
        sys.stdout.flush()
        sys.stderr.flush()
        os.kill(os.getpid(), 9)
    t = threading.Thread(target=thread_worker)
    t.daemon = True
    t.start()
    if options.sleep:
        time.sleep(1000000)
    else:
        while 1:
            pass
    print("main thread exit")
    sys.stdout.flush()
    sys.stderr.flush()
    pass

if __name__ == '__main__':
    main(sys.argv[1:])
